package mm.chenchen.modules.file.controller;

import lombok.extern.slf4j.Slf4j;
import mm.chenchen.common.utils.FileUtils;
import mm.chenchen.common.utils.MinioClientUtil;
import mm.chenchen.common.utils.R;
import mm.chenchen.modules.file.entity.FileInfoEntity;
import mm.chenchen.modules.file.service.FileInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

@RestController
@Api("BillingCost")
@RequestMapping("file")
@CrossOrigin
@Slf4j
public class FileController {


    @Autowired
    private ServletContext servletContext;
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private MinioClientUtil minioClientUtil;


    @ApiOperation(value = "导入单个文件,及其简单")
    @PostMapping(value = "/import")
    public R importExcel(@RequestParam("file") MultipartFile file) {
        return null;
    }


    @ApiOperation(value = "上传文件", notes = "支持多个文件上传")
    @RequestMapping("/upload")
    public R uploadFile(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        ServletFileUpload.isMultipartContent(request);
        MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
        Map<String, MultipartFile> filemm = multipartRequest.getFileMap();
        Iterator<MultipartFile> ii = filemm.values().iterator();
        while (ii.hasNext()) {
            FileInfoEntity fileInfoEntity = FileUtils.uploadFileToMinio(minioClientUtil.getMinioClient(), ii.next(),"");
            if (fileInfoEntity != null) {
                fileInfoService.save(fileInfoEntity);
            }
        }
        return R.ok();
    }

    @ApiOperation(notes = "N下载文件", value = "下载文件单个")
    @RequestMapping(value = "/file")
    public void downloadFileFromMinio(@RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {

        String minioId = String.valueOf(params.get("minioId"));
        String fileName = String.valueOf(params.get("fileName"));

        HttpHeaders headers = new HttpHeaders();// http协议
        headers.setContentDispositionFormData("attachment", fileName);
        InputStream inputStream = FileUtils.downloadFromMinio(minioClientUtil.getMinioClient(), minioId, FileUtils.getSuffix(fileName));
        BufferedInputStream br = new BufferedInputStream(inputStream);
        byte[] buf = new byte[1024];
        int len = 0;
        response.reset(); // 非常重要
        response.setCharacterEncoding("UTF-8");

        response.setHeader("conent-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Access-Control-Allow-Origin", "*");
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        br.close();
        out.close();
        inputStream.close();
    }

    @ApiOperation(notes = "NOT_EXIST_DATA:文件数据为空", value = "下载文件")
    @RequestMapping(value = "/downloadFile")
    public void downloadFile(@RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {

        // 文件名称
        String name = "jdk-8u162-windows-x64.exe";
        HttpHeaders headers = new HttpHeaders();// http协议
        // 文件路径
        String path = "E:\\software\\jdk-8u162-windows-x64.exe";
        // name = new String(name.getBytes("UTF-8"),"ISO-8859-1");
        File f = new File(path);


        // 纯下载方式
        //获取浏览器名（IE/Chome/firefox）
        //String userAgent = request.getHeader("User-Agent");
//        if(userAgent.contains("MSIE")||userAgent.contains("Trident")) {
//            //针对IE或IE为内核的浏览器
//            name= URLEncoder.encode(name,"UTF-8");
//        }else {
//            //谷歌控制版本
//            name=new String(name.getBytes("UTF-8"),"ISO-8859-1");
//        }
        // 默认下载文件名为原始文件名
        headers.setContentDispositionFormData("attachment", name);
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        response.reset(); // 非常重要
        response.setCharacterEncoding("UTF-8");

        //name=new String(name.getBytes("UTF-8"),"ISO-8859-1");
        response.setHeader("conent-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Access-Control-Allow-Origin", "*");
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        br.close();
        out.close();
        return;
    }

}

